package com.losdun.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.product.domain.AttributeParts;
import com.losdun.product.domain.vo.AttributePartsVo;
import com.losdun.product.mapper.AttributePartsMapper;
import com.losdun.product.service.AttributePartsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sword.ye
 * @date 2025/4/24
 **/
@Service
@Slf4j
public class AttributePartsServiceImpl extends ServiceImpl<AttributePartsMapper, AttributeParts> implements AttributePartsService {

    @Override
    public List<AttributePartsVo> getAttributeParts(Long attrId) {
        LambdaQueryWrapper<AttributeParts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttributeParts::getAttrId, attrId).orderByAsc(AttributeParts::getConfigOrderNo,AttributeParts::getPartCode);
        List<AttributePartsVo> retList = new ArrayList<>();
        List<AttributeParts> attrPartsList = baseMapper.selectList(queryWrapper);
        LinkedHashMap<Long, List<AttributeParts>> configGroup= attrPartsList.stream()
                .collect(Collectors.groupingBy(AttributeParts::getConfigId,LinkedHashMap::new,Collectors.toList()));
        for (Map.Entry<Long, List<AttributeParts>> entry : configGroup.entrySet()) {
            AttributePartsVo attributePartsVo = new AttributePartsVo();
            attributePartsVo.setConfigId(entry.getKey());
            List<AttributeParts> groupPartsList = entry.getValue();
            attributePartsVo.setConfigName(groupPartsList.get(0).getConfigName());
            attributePartsVo.setDefaultImageUrl(groupPartsList.get(0).getConfigImageUrl());
            List<AttributePartsVo.PartsTreeNode> treeNode = buildTree(groupPartsList);
            attributePartsVo.setPartsList(treeNode);
            retList.add(attributePartsVo);
        }
        return retList;
    }

    @Override
    public List<AttributeParts> queryAttributeParts(Long attrId) {
        LambdaQueryWrapper<AttributeParts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttributeParts::getAttrId, attrId)
                .orderByAsc(AttributeParts::getConfigOrderNo,AttributeParts::getPartCode);
        return baseMapper.selectList(queryWrapper);
    }


    private static List<AttributePartsVo.PartsTreeNode> buildTree(List<AttributeParts> objects) {
        Map<String, AttributePartsVo.PartsTreeNode> nodeMap = new HashMap<>();
        List<AttributePartsVo.PartsTreeNode> roots = new ArrayList<>();

        // 第一遍：创建所有节点并存入map
        for (AttributeParts obj : objects) {
            String code = obj.getPartCode();
            AttributePartsVo.PartsTreeNode node = new AttributePartsVo.PartsTreeNode(code);
            node.setValue(obj.getPartsId());
            node.setName(obj.getPartName());
            node.setRemark(obj.getPartRemark());
            node.setPrice(obj.getPartPrice());
            node.setUnit(obj.getPartUnit());
            node.setImageUrl(obj.getPartImageUrl());
            nodeMap.put(code, node);
        }

        // 第二遍：建立父子关系
        for (AttributeParts obj : objects) {
            String code = obj.getPartCode();
            AttributePartsVo.PartsTreeNode node = nodeMap.get(code);
            // 判断是否是根节点（code长度为2或3）
            if (code.length() == 5) {
                roots.add(node);
            } else {
                // 获取父节点code
                String parentCode = getParentCode(code);
                AttributePartsVo.PartsTreeNode parent = nodeMap.get(parentCode);
                if (parent != null) {
                    parent.getChildren().add(node);
                }
            }
        }
        return roots;
    }

    private static String getParentCode(String code) {
        if (code.length() == 7) {
            return code.substring(0, 5); // 处理P14, P15等一级节点
        } else if (code.length() == 9) {
            return code.substring(0, 7); // 处理P1401, P1501等二级节点
        }
        return null;
    }


}
